package com.cloudkinto.appletservice.fbaorderoutput.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.appletservice.fbaorderoutput.AppletFbaOrderOutputService;
import com.cloudkinto.appletservice.fbaorderoutput.vo.AppletOrderOutputDetailRes;
import com.cloudkinto.appletservice.fbaorderoutput.vo.AppletOrderOutputListRes;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.DicBusinessItemDo;
import com.cloudkinto.entity.FbaOrderOutputDo;
import com.cloudkinto.entity.FbaStorageDo;
import com.cloudkinto.entity.StorageDo;
import com.cloudkinto.service.file.FileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-04
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AppletFbaOrderOutputServiceImpl extends ServiceImpl<FbaOrderOutputDao, FbaOrderOutputDo> implements AppletFbaOrderOutputService {
    private static final String SHIPMENT_TYPE_0 = "普通";
    private static final String SHIPMENT_TYPE_1 = "次日达";
    private static final String ORDER_OUTPUT_TYPE_2 = "FBA转运";
    private static final String ORDER_OUTPUT_TYPE_1 = "一件代发";
    @Autowired
    private FbaOrderOutputDao dao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private OrderOutputPackageDao packageDao;
    @Autowired
    private OrderOutputProductDao productDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private FbaStorageDao fbaStorageDao;


    @Override
    public AppletOrderOutputDetailRes detail(Long id) {
        FbaOrderOutputDo entityDo = dao.selectById(id);
        AppletOrderOutputDetailRes res = new AppletOrderOutputDetailRes();
        if (entityDo == null) throw new BizExceptionI18("no.order.info");
        BeanUtils.copyProperties(entityDo, res);
//        res.setFileUrl(fileService.getFilePath(entityDo.getFileId()));
        return handlerDetailAfter(entityDo, res);
    }

    //查询明细之后要执行的业务定制处理
    private AppletOrderOutputDetailRes handlerDetailAfter(FbaOrderOutputDo entityDo, AppletOrderOutputDetailRes res) {
        if (shopDao.selectById(entityDo.getShopId()) != null) {
            res.setShop(shopDao.selectById(entityDo.getShopId()).getShopName());
        }
        if (storageDao.selectById(entityDo.getStorageId()) != null) {
            res.setStorage(storageDao.selectById(entityDo.getStorageId()).getStorageName());
        }
        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(entityDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorage(fbaStorageDo.getFbaCode());
        }
        if (dicBusinessItemDao.selectById(entityDo.getTrackId()) != null) {
            res.setTrackName(dicBusinessItemDao.selectById(entityDo.getTrackId()).getDicItemValue());
        }
        res.setPoNumber(entityDo.getPoNumber());
        res.setOrderNo(entityDo.getOrderNo());
        res.setReceiverName(fbaStorageDo.getFbaName());
        res.setPostCode(fbaStorageDo.getPostCode());
        res.setTelPhone(fbaStorageDo.getTelPhone());
        res.setAddress(fbaStorageDo.getAddress());
        if (entityDo.getDeliveryDate() != null)
            res.setDeliveryDate(TimeUtils.formatDate(entityDo.getDeliveryDate()));
        res.setOrderNumber(entityDo.getFbaOrderOutputNumber());
//        res.setOrderTypeName(entityDo.getOrderType() != null && entityDo.getOrderType() == 2 ? ORDER_OUTPUT_TYPE_2 : ORDER_OUTPUT_TYPE_1);
//        res.setShipmentTypeName(entityDo.getShipmentType() != null && entityDo.getShipmentType() == 1 ? SHIPMENT_TYPE_1 : SHIPMENT_TYPE_0);
        //查询对应包裹列表
        QueryWrapper packageWrapper = new QueryWrapper();
        packageWrapper.eq("order_output_id", res.getId());
        //package
//        List<OrderOutputPackageDo> packageDoList = packageDao.selectList(packageWrapper);
//        List<OrderOutputPackageDetail> packageResList = new ArrayList<>();
//        for (OrderOutputPackageDo packageDo :
//                packageDoList) {
//            OrderOutputPackageDetail packageDetailRes = new OrderOutputPackageDetail();
//            BeanUtils.copyProperties(packageDo, packageDetailRes);
//            packageDetailRes.setCount(packageDo.getCount());
//            packageDetailRes.setSize(packageDo.getLength() + "+" + packageDo.getWidth() + "+" + packageDo.getHeight());
//            //product
//            List<OrderOutputProductDetail> productResList = new ArrayList<>();
//            QueryWrapper productWrapper = new QueryWrapper();
//            productWrapper.eq("package_id", packageDo.getId());
//            List<OrderOutputProductDo> productDoList = productDao.selectList(productWrapper);
//            for (OrderOutputProductDo productDetail : productDoList) {
//                OrderOutputProductDetail productDetailRes = new OrderOutputProductDetail();
//
//                BeanUtils.copyProperties(productDetail, productDetailRes);
//                ProductInfoDo productInfoDo = productInfoDao.selectById(productDetail.getProductId());
//                if (productInfoDo != null) {
//                    productDetailRes.setCommoditySku(productInfoDo.getCommoditySku());
//                    productDetailRes.setStorageSku(productInfoDo.getStorageSku());
//                    productDetailRes.setCommodityName(productInfoDo.getCommodityName());
//                }
//
//                productResList.add(productDetailRes);
//            }
//            packageDetailRes.setProductList(productResList);
//            packageResList.add(packageDetailRes);
//        }
//
//        res.setPackageList(packageResList);


//        //查询日志
//        List<OperateRes> operateResList = new ArrayList<>();
//        LambdaQueryWrapper<OperateRecordDo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(OperateRecordDo::getThirdId, entityDo.getId()).eq(OperateRecordDo::getType, 3).orderByDesc(OperateRecordDo::getId);
//        List<OperateRecordDo> operateRecordDos = operateRecordDao.selectList(queryWrapper);
//        if (!CollectionUtils.isEmpty(operateRecordDos)) {
//            for (OperateRecordDo operateRecordDo : operateRecordDos) {
//                OperateRes operateRes = new OperateRes();
//                operateRes.setOperateTime(operateRecordDo.getOperateTime());
//                operateRes.setContent(operateRecordDo.getContent());
//                UserDo userDo = userDao.selectById(operateRecordDo.getOperateBy());
//                if (userDo != null) {
//                    operateRes.setOperateBy(userDo.getUserName() == null ? userDo.getUserAccount() :
//                            userDo.getUserName());
//                }
//                operateResList.add(operateRes);
//            }
//        }
//        res.setOperateResList(operateResList);
        return res;
    }


    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FbaOrderOutputDo> wrapper = queryBuild(map);
        IPage<FbaOrderOutputDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<AppletOrderOutputListRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }


    //查询分页列表之后对列表数据的处理
    private List<AppletOrderOutputListRes> handlerListAfter(List<FbaOrderOutputDo> list) {
        List<AppletOrderOutputListRes> result = new ArrayList<>();
        for (FbaOrderOutputDo orderOutputDo :
                list) {
            AppletOrderOutputListRes listRes = new AppletOrderOutputListRes();
            BeanUtils.copyProperties(orderOutputDo, listRes);
            StorageDo storageDo = storageDao.selectById(orderOutputDo.getStorageId());
            if (storageDo != null) {
                listRes.setStorageName(storageDo.getStorageName());
            }
            FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(orderOutputDo.getFbaStorageId());
            if (fbaStorageDo != null) {
                listRes.setFbaStorageName(fbaStorageDo.getFbaCode());
            }
            DicBusinessItemDo dic = dicBusinessItemDao.selectById(orderOutputDo.getTrackId());
            if (dic != null) {
                listRes.setTrackName(dic.getDicItemValue());
            }
            DicBusinessItemDo dicBusinessItemDo = dicBusinessItemDao.selectById(orderOutputDo.getStatus());
            if (dicBusinessItemDo != null) {
                listRes.setStatus(dicBusinessItemDo.getDicItemValue());
            }
            listRes.setNumber(orderOutputDo.getFbaOrderOutputNumber());
            listRes.setSendDate(TimeUtils.formatDate(orderOutputDo.getSendDate()));
            listRes.setPoNumber(orderOutputDo.getPoNumber());
            listRes.setShipPrice(orderOutputDo.getShipFee());
            result.add(listRes);
        }
        return result;
    }


    private IPage<FbaOrderOutputDo> pageInit(Map<String, String> map) {
        IPage<FbaOrderOutputDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FbaOrderOutputDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FbaOrderOutputDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.or(orderOutputDoQueryWrapper -> orderOutputDoQueryWrapper.like("order_no", map.get("keyword").trim()).or(true)
                    .like("order_output_number", map.get("keyword").trim()).or(true)
                    .like("tel_phone", map.get("keyword").trim()).or(true)
                    .like("track_number", map.get("keyword").trim()).or(true)
                    .like("receiver_name", map.get("keyword").trim()));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("send_date", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("send_date", map.get("endDate"));
        }
        if (StringUtils.isNotBlank(map.get("storageId"))) {
            wrapper.eq("storage_id", map.get("storageId"));
        }
        if (StringUtils.isNotBlank(map.get("trackId"))) {
            wrapper.eq("track_id", map.get("trackId"));
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        }

        wrapper.eq("company_id", map.get("companyId"));

        wrapper.orderByDesc("id");
        return wrapper;
    }


}
